<template>

  <div class="wrap">
    <section class="header">
      <el-row>
        <el-col :span="20">
          <ProductionSteps :active="3" align-center/>
        </el-col>

        <el-col :span="4">
          <div style="display: flex;justify-content: flex-end;margin-right: 30px;padding-top: 10px">
            <el-popover
              placement="bottom"
              v-model="emptyProvVisible"
              width="200">
              <p style="margin-bottom: 10px">请确认是否清空格子？</p>
              <div style="text-align: right; margin: 0">
                <el-button :loading="loadingEmptyCellsBtn" @click="emptyCells" size="mini" type="danger">确定</el-button>
                <el-button @click="emptyProvVisible = false" size="mini" type="info">取消</el-button>
              </div>
              <el-button slot="reference" type="primary">清空格子</el-button>
            </el-popover>

            <a-button :disabled="true" plain size="medium" style="margin-left: 10px" type="danger">返工</a-button>
            <a-button
              @click="shuffle" size="medium"
              style="margin-left: 10px" type="warning" v-if="+$route.query.dev===333">change the world
            </a-button>

          </div>
        </el-col>
      </el-row>
    </section>

    <section class="help">
      <HeaderHelpDoc :head-context="headContext"/>
    </section>

    <el-row :gutter="30" class="main-wrap">
      <el-col :span="16" class="main-left">
        <el-row class="scan">

          <el-col class="operator-area">
            <span>
              <span style="padding-right: 30px">
                <el-radio label="1" v-model="radio">产品首尾扫描</el-radio>
              </span>
              <span>
                <span>请扫描SN条码: </span>
                <el-input
                  @keydown.native.enter="scanOrInputBarcode"
                  clearable placeholder="点击此处开始扫描"
                  style="width: 270px" v-loading="loadingScan"
                  v-model="scanBarcode">
                    <el-button icon="el-icon-search" slot="append" type="primary"></el-button>
                </el-input>
              </span>

              <span style="padding-left: 30px">下一道工序:</span>
              <span style="padding: 15px">
<!--       insideVolumeProductSorting         -->
                <a-button
                  @click="$router.push({name:'insidePagesVolume'})">内页册成册</a-button>
              </span>
              <!--         style="width: 200px;position: relative"     -->

               <a-button @click="scanBarcodeArr=[]"
                         type="info">清空扫描</a-button>

              <!--              <div style="margin-left: 15px;display: inline-block">-->
              <!--                <span style="margin-right: 10px;">提示:</span>-->
              <!--                <transition-group name="azure-slide" style="position: relative;display: inline-block"-->
              <!--                                  tag="div">-->
              <!--                  <el-tag :key="e" :type="scan_tips[e]['status']" class="azure-slide-item"-->
              <!--                          v-for="e in Object.keys(scan_tips)" v-if="+e === scanBarcodeArr.length">-->
              <!--                        {{scan_tips[e].tip}}-->
              <!--                  </el-tag>-->
              <!--                </transition-group>-->
              <!--              </div>-->

              <!--     <span>分拣储位:</span>-->
            </span>
          </el-col>

          <el-col class="condition-filter">
            <el-input
              @keydown.native.enter="scanOrInputBarcode" clearable
              placeholder="请输入内容" style="width: 300px" suffix-icon="el-icon-search"
              v-model="searchKey"/>

            <line-select :value.sync="selectedLineBody" style="margin-left: 30px;width: 230px"/>

          </el-col>

          <el-col class="show-work-sit">
            <work-sit-info :workStationData="workStationData"/>
          </el-col>

          <el-col class="album-grid">

            <transition-group
              class="album-grid-wrap"
              name="list-complete" tag="el-row">
              <el-col
                :key="cell['GridId']"
                :span="6"
                class="list-complete-item" style="max-height: 134px"
                v-for="(cell,idx) in cellList">


                <!--    isNotFill(cell) ? 'orange' : '#1890ff',   -->
                <el-card
                  :body-style="{height:'100%'}"
                  v-bind:style="{ color: '#ffffff',
                   background:
                   cellColor(cell),
                   position:'relative',
                   height:'132px'
                }">

                  <template v-if="cell['CtmName']!==null">

                    <!--  v-show="isNotFill(cell)" -->
                    <i
                      :style="iconStyle()"
                      @click.stop="patchRestProd(cell,idx)"
                      class="el-icon-circle-plus"
                      v-show="isNotFill(cell)"></i>

                    <div class="text-break" style="display: flex;justify-content: center;font-weight: bolder">
                      {{cell['GridName']}}
                    </div>

                    <div class="text-break" style="padding-top:3px;">产品编码： {{cell.OrderProductCode}}</div>
                    <div class="text-break" style="padding-top:3px;">产品名称： {{cell.OrderProductName}}</div>

                    <el-tooltip :content="cell['CtmName']" :disabled="!(cell['CtmName'] && cell['CtmName'].length>7) ">
                      <div class="text-break" style="padding-top:3px;">客户名称： {{cell['CtmName']}}</div>
                    </el-tooltip>

                    <div class="text-break" style="padding-top:3px;">&nbsp;&nbsp;&nbsp;&nbsp;照片数：{{showPhoto(cell)}}
                    </div>
                  </template>

                  <template v-else>
                    <div style="height:100%;display: flex;
                    justify-content: center;font-weight: bolder;align-items: center;font-size: 19px">
                      {{cell['GridName']}}
                    </div>
                  </template>

                </el-card>


              </el-col>
            </transition-group>
          </el-col>

        </el-row>
      </el-col>

      <el-col :span="8" class="main-right">
        <el-tabs type="border-card">
          <el-tab-pane label="可加工的产品">
            <section>
              <div style="margin-bottom: 5px">订单号:</div>
              <div>客户名称:</div>
            </section>
            <azure-dynamic-table :column-des-objs="columnDesObjs" :data="tableData"/>
          </el-tab-pane>
          <el-tab-pane label="作业指导书">
            作业指导书
          </el-tab-pane>
        </el-tabs>
      </el-col>
    </el-row>

  </div>

</template>

<script>
  import ProductionSteps from '@/views/productManagement/aComponents/ProductionSteps'
  import HeaderHelpDoc from '@/components/ATheFridayClub/HeaderHelpDoc'
  import AButton from '@/components/ATheFridayClub/AButton'
  import LineSelect from '@/components/ATheFridayClub/businessRelation/LineSelect'
  import WorkSitInfo from '@/components/ATheFridayClub/businessRelation/WorkSitInfo'
  import {
    cleanProductPhotoGrid,
    getProductGridAutoList, ScanProductGridEnd,
    ScanProductGridPhoto
  } from '@/api/factoryPresetScan'
  import AzureDynamicTable from '@/components/ATheFridayClub/mDynamicTable/AzureDynamicTable'
  import { ERR_OK } from '@/utils/commons'
  import _ from 'lodash'
  import lineBodyRelate from '@/mixins/lineBodyRelate'

  //  keys 之后key全部都是字符串
  const SCAN_ERR_MESSAGE = {
    101: '第一次扫描的照片已经在格子里,第二次扫描的不是最后一张',
    102: '第一张照片新增失败',
    103: '第一次扫描的是组件中的第一张照片，第二次扫描不是最后一张',
    104: '扫描的第一张照片不在格子里且不是第一张，请扫描第一张',
    105: '组件照片尾码不是组件的最后一张照片，请扫描最后一张',
    106: '照片条码首尾扫描失败',
    107: '更新格子状态失败',
    108: '提交流程失败',
    109: '组件照片信息为空',
    110: '首尾组件照片号不是同一个产品',
    111: '组件照片分拣失败'
  }

  const scan_tips = {
    0: { tip: '请扫描头码', tag: 'el-tag', status: 'info' },
    1: { tip: '已扫描头码', tag: 'el-tag', status: 'success' },
    2: { tip: '已扫描尾码', tag: 'el-tag', status: 'primary' }
  }
  const colorMap = {
    'full': '#67C23A',
    'half': '#E6A23C',
    'empty': '#1890ff'
  }

  export default {
    name: 'factoryPresetScan',
    components: { AzureDynamicTable, WorkSitInfo, LineSelect, AButton, HeaderHelpDoc, ProductionSteps },
    mixins: [lineBodyRelate],

    $_techType: 6, //  线体使用,放在options中保险一些

    data() {

      return {
        // techType: 6, //  线体使用
        selectedLineBody: '', //  线体使用,用户选择的线体

        headContext: '工厂前台扫描是针对双面印的页面,而单面印对应的页面则是输出分拣',
        radio: '1',

        scanBarcode: '', //  用户扫描或输入的条形码

        workStationData: {},  //  工位的信息

        tableData: [],

        columnDesObjs: [
          // { label: '材料价格(元)', key: 'costPrice', filter: moneySuffix },
          { key: 'prodName', label: '产品名称' },
          { key: 'prodName2', label: 'SN条形码' },
          { key: 'prodName3', label: '规格' },
          { key: 'prodName4', label: '张数' },
          { key: 'prodName5', label: '订单号' }
          // { key: 'createBy', label: '创建人' },
          // { key: 'createTime', label: '创建时间', dateFormat: true},
          // { key: 'updateBy', label: '修改人' },
          // { key: 'updateTime', label: '修改时间', width: 230, dateFormat: true },
          // { label: '操作', key: 'operator', width: 180 }
        ],

        scanBarcodeArr: [], //  长度只能为 2
        loadingScan: false,

        loadingEmptyCellsBtn: false,
        emptyProvVisible: false,

        searchKey: '',

        cellList: [],  //  格子数据

        scan_tips
      }
    },
    created() {
      this.getProductGridList() //  格子初始化

      // console.log('格子初始化');
      // this.$speakText('格子初始化')
    },
    methods: {
      cellColor(cell) {

        const { CtmName } = cell
        if (CtmName === null) {
          return colorMap['empty']
        }
        return colorMap[this.isNotFill(cell) ? 'half' : 'full']
      },

      iconStyle() {
        //   color: '#67C23A',
        return {
          position: 'absolute', right: '5px', top: '5px',
          cursor: 'pointer', fontSize: '22px'
        }
      },

      async patchRestProd(cell, idx) {
        const { GridId } = cell
        try {

          const { value: orderFileEnd } =
            await this.$prompt(`输入'${cell['GridName']}'格子的尾码让格子过站`,
              '请扫描或输入尾码', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                inputPattern: /^[a-z0-9]+$/i,
                inputErrorMessage: '请输入正确格式的code'
              }).catch((e) => {
              console.log('>>>>>>>> catch')
              console.log(e)
            })

          //  GridId   orderFileEnd
          const { Code, Message, Result } = await ScanProductGridEnd({ GridId, orderFileEnd })
          if (+Code === ERR_OK) {
            this.$message.success(Message)
            await this.getProductGridList() //  初始化数据
          }
        } catch (e) {
          console.log(e)
        }

      },
      //  格子是否没有被填满
      isNotFill(cell) {
        //  cell
        return cell['SnCount'] > 0 && cell['SnCount'] < cell['MaxCount']
      },
      showPhoto(cell) {
        let template = ''
        if (cell['MaxCount'] !== 0) {
          template = `${cell['SnCount']} / ${cell['MaxCount']}` //  1-
        }
        return template
        // return `1-1/${cell['SnCount']}`
      },
      shuffle() {
        this.cellList = _.shuffle(this.cellList)
      },

      //  格子初始化
      async getProductGridList() {
        // await getProductGridList({ OrderFileId })
        try {
          const { Code, Result } = await getProductGridAutoList()
          if (+Code === ERR_OK) {
            this.cellList = Result
          }
        } catch (e) {
        }
      },

      //  清空全部的格子
      async emptyCells() {
        try {
          this.loadingEmptyCellsBtn = true
          const { Code, Message, Result } = await cleanProductPhotoGrid()

          if (+Code === ERR_OK) {
            this.$message.success(Message)
            this.emptyProvVisible = false

            this.getProductGridList()

            // this.cellList.forEach(e => {
            //   Object.keys(e).map((key) => {
            //     if (e.hasOwnProperty(key)) {
            //       const ignore = ['GridName', 'GridId']
            //       if (!ignore.includes(key)) {
            //         e[key] = ''
            //       }
            //       if (key === 'MaxCount') {
            //         e[key] = 0
            //       }
            //     }
            //   })
            // })

          }
        } catch (e) {
          console.log(e)
          // this.emptyProvVisible = false;
        } finally {
          setTimeout(() => {
            this.loadingEmptyCellsBtn = false
          }, 1000)
        }
      },

      //  用户使用扫描枪 或者 手动输入
      async scanOrInputBarcode({ target: { value } }) {
        // const { value: code } = e.target

        console.log(value)

        const strategy = {
          ['double']: async(value) => {
            //  当前已经有两个值了,第二次的值不push进入数组
            if (this.scanBarcodeArr.length === 1) {
              const firstScanCode = _.head(this.scanBarcodeArr)
              // const lastScanCode = _.last(this.scanBarcodeArr)

              try {
                const { Code, Message, Result, ErrorCode } = await ScanProductGridPhoto({
                  orderFileStart: firstScanCode, orderFileEnd: value
                })
                // if (+Code === ERR_OK) {
                //   if ([103].includes(+ErrorCode)) {
                //     // this.scanBarcodeArr = _.dropRight(this.scanBarcodeArr)  //  创建数组切片
                //     //  因为第二次的值直接传给了服务端,并没有存下来,所以不需要删除
                //   }
                // } else {
                //   //  code === 0 condition
                // }
                //  code===1 || errCode===103
                // const isSuc = (() => {
                //   //  (!Object.keys(SCAN_ERR_MESSAGE).includes(`${ErrorCode}`))
                //   return (+Code===1) || (+ErrorCode === 103)
                // })()

                const isSuc = (+Code === ERR_OK)

                //  tips dependency server
                this.$message({
                  type: (() => {
                    return isSuc ? 'success' : 'error'
                  })(),
                  message: Message
                  //   (() => {
                  //   return +ErrorCode === 0 ? Message :   SCAN_ERR_MESSAGE[+ErrorCode]
                  // })()
                })

                if (isSuc) {
                  this.$speakText('格子已过站')
                } else {
                  this.$speakText('尾码格式有错误')
                  if (+ErrorCode === 105) {
                  }
                }

                //  成功的情况,调用初始化接口
                isSuc && await this.getProductGridList()

                //  执行完成第二次之后,无论结果如何,清空temp数组,不然服务器不好来判断
                this.scanBarcodeArr = []
              } catch (e) {
                //  如果发生异常,不做任何操作,因为第二次的值没有被保存下来
                console.log(e)
              }
            } else if (this.scanBarcodeArr.length === 0) {
              //  用户首次输入,只是装入值
              this.scanBarcodeArr.push(value)
            }
            this.scanBarcode = ''

          },
          ['single']: async(value) => {
            try {
              console.log(this)
              console.log(this.scanBarcode)
              const { Code, Message, Result, ErrorCode } = await ScanProductGridPhoto({
                orderFileStart: value, orderFileEnd: value
              })

              const isSuc = (+Code === ERR_OK)

              //  tips dependency server
              this.$message({
                type: (() => {
                  return isSuc ? 'success' : 'error'
                })(),
                message: Message
              })

              if (isSuc) {
                this.$speakText('格子已过站')
              } else {
                this.$speakText('尾码格式有错误')
              }

              //  成功的情况,调用初始化接口
              isSuc && await this.getProductGridList()
            } catch (e) {
              console.log(e)
            } finally {
              this.scanBarcode = ''
            }

          }
        }

        await strategy['single'](value)

      }

    }
  }
</script>


<style lang="scss" scoped>
  @import "~@/styles/index.scss";

  .wrap {

    .text-break {
      cursor: pointer;
      @include noWrap()
    }

    .header {

      padding: 10px 0;
    }

    .help {
      padding: 10px;
    }

    .main-wrap {
      padding: 10px;
      font-size: $mainSize;

      .main-left {
        min-width: 840px;

        .scan {
          .operator-area {
            padding: 15px 10px;
            border: 1px solid $borderColor;
            border-radius: 3px;
          }

          .condition-filter {
            /*margin: 30px 0;*/
            padding: 30px 0;
          }

          .album-grid {
            .album-grid-wrap {
              padding: 30px 0;
            }

          }
        }
      }

      .main-right {

        min-width: 350px;
      }

    }

  }

</style>
